#include <iostream>
#include "Server.h"

Server::Server(io_context &ioContext, const short port)
    : _ioc(ioContext),
      _acceptor(ioContext, tcp::endpoint(tcp::v4(), port)) {
    StartAccept();
    clog << "服务启动，端口 " << port << endl;
}

void Server::StartAccept() {
    auto &ioc = IOServicePool::GetInstance().GetIOContext();
    shared_ptr<Session> session = make_shared<Session>(_ioc, this);

    _acceptor.async_accept(session->GetSocket(), [this, session](const boost::system::error_code &ec) {
        HandleAccept(session, ec);
    });
}

void Server::HandleAccept(const shared_ptr<Session> &session, const boost::system::error_code &ec) {
    if (!ec) {
        session->Start();
        clog << "新连接，uuid = " << session->GetUuid() << endl;
        _session_map.insert(make_pair(session->GetUuid(), session));
    }
    else {
        cerr << "连接失败, " << ec.message() << endl;
    }
    StartAccept();
}

void Server::ClearSession(const string &uuid) {
    _session_map.erase(uuid);
}
